package no.mehdi.usereg.web.form;

import java.io.Serializable;
import java.util.EventListener;
import java.util.EventObject;

import no.mehdi.usereg.rfid.controllers.RFIDController;
import no.mehdi.usereg.rfid.exceptions.RFIDException;

import org.ajax4jsf.event.PushEventListener;

public class ControlForm implements Serializable, Runnable{

	private static final long serialVersionUID = 1L;
	Thread thread;
	private boolean listnerStarted;
	PushEventListener listener;
	
	private RFIDController rfid;
	
	private int snr;

    public PushEventListener getListener() {
		return listener;
	}

	public void setListener(PushEventListener listener) {
		this.listener = listener;
	}

	public int getSnr() {
		return snr;
	}

	public void setSnr(int snr) {
		this.snr = snr;
	}

	public void addListener(EventListener listener) {
        synchronized (listener) {
            if (this.listener != listener) {
                this.listener = (PushEventListener) listener;
            }
        }
    }
	
	public void startListner() throws Exception{
		System.out.println("Started huhu");
		thread = new Thread(this);
		thread.setDaemon(true);
		thread.start();
		
		this.setListnerStarted(true);
	}
	public void stopListner(){
		System.out.println("Stopped huhu");
		try {
			
			rfid.setAntennaOff();
			rfid.setLedOff();
			rfid.stopRfid();
			thread = null;
		} catch (RFIDException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.setListnerStarted(false);
	}
	
	public void fireListner(){
		listener.onEvent(new EventObject(this)); 
	}
	
	public void setListnerStarted(boolean listnerStarted) {
		this.listnerStarted = listnerStarted;
	}
	public boolean isListnerStarted() {
		return listnerStarted;
	}

	public void setRfid(RFIDController rfid) {
		this.rfid = rfid;
	}

	public RFIDController getRfid() {
		return rfid;
	}

	@Override
	public void run() {
		try {
			rfid.startRfid();
			rfid.setAntennaOn();
			rfid.setLedOn();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
		}
	}
	
}
